package cn.com.session;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.catalina.User;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "session02", value = "/session02")
public class session02 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 获取Session对象
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();

        // 从Session中获取数据，使用getAttribute方法
        String username = (String) session.getAttribute("username");
        Integer userid = (Integer) session.getAttribute("userid");
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");

        // 获取自定义对象（需要强制类型转换）
        User currentUser = (User) session.getAttribute("currentUser");

        // 判断Session中是否存在某个属性
        if (session.getAttribute("username") != null) {
            // 存在该属性
            out.print("用户名：" + username + "<br>");
            out.print("用户ID：" + userid + "<br>");
            out.print("是否登录：" + isLogin + "<br>");
        } else {
            // 不存在该属性
            out.print("Session中没有该属性");

        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
